var bIsSelected = false;
var tianbaoCart = 'https://cart.tmall.com/'
var scopeStr = 'tmall.com';
var pound = '#';

//检测状态
function checkElementState(path, callback) {
    var ele = document.querySelector(path);
    if (ele) {
        callback && callback();
    } else {
        console.log('异步加载元素中....' + path);
        setTimeout(function () {
            checkElementState(path, callback);
        }, 50);
    }
}


//点击购买按钮
function clickBuy() {

    console.log('买！');

    //票的数量  如果还不可以购买，这个地方获取会失败 
    var amount = document.getElementsByClassName('mui-amount-increase')[0];
    amount && amount.click();  //+1

    var btnBuy = document.querySelector('');

}


//结算
function checkOut() {

		console.log('结算开始....');
		var btn = document.getElementById('J_Go');

		if (btn) {
		
			var readState = document.readyState;
			console.log('readState=' + readState);
			if( readState == 'complete' || readState == 'interactive'){
					btn.click();
						
			}	
		} else {
        console.log('结算按钮没找到');
		}
	

}

function checkOutAsync() {
    checkElementState('#J_Go', checkOut);
}

//提交订单
function submitOrder() {

    console.log('提交订单开始....');


    checkElementState('.go-btn', function () {
        var btn = document.querySelector('.go-btn');
        if (btn) {
            btn.click();
            setTimeout(function () {
                main();
            }, 50);
        } else {
            console.log('提交订单按钮没找到');
            setTimeout(function () {
                submitOrder();
            }, 50);
        }

    });
}


//dDate.setSeconds( dDate.getSeconds() + 10 );

//进入时间判断循环
function enterTimeCheckLoop(callback) {

    try{
        var date = new Date();

        //目标时间
        var dDate = new Date();  //20点开抢
        dDate.setHours(19, 59, 59.2);
        //当前时间
        var currentHour = date.getHours();

        console.log('currentHour=' + currentHour);

        if(currentHour != 19 && currentHour != 20){
            //模拟浏览网页
            setTimeout(function () {
                simulate();
            }, 900000);
        }else{
            var diff = Date.parse(dDate) - Date.parse(date);
            if(!bIsSelected){
                bIsSelected = selectAllProduct();
                console.log("bIsSelected=" + bIsSelected);
            }

            if (diff < -900) {

                console.log('时间过了！');
                refreshLoc(date);
                selectAllProduct();
                setTimeout(function () {
                    enterTimeCheckLoop(callback);
                }, 400);

            } else if (diff < 500 && bIsSelected) {
                //selectAllProduct();
                callback && callback();
                console.log('时间到了！！！');

            } else {
                //selectAllProduct();
                refreshLoc(date);
                setTimeout(function () {
                    enterTimeCheckLoop(callback);
                }, 400);

                //console.log('--');
            }
        }
    }catch (e) {
        console.error(e);
    }


}


//模拟浏览页面
function simulate() {

    try{
        //当前时间
        var date = new Date();

        //当前时间
        var currentHour = date.getHours();
        console.log("模拟浏览=" + currentHour);
        if (currentHour == 19 || currentHour == 20) {
            console.log("进入抢购=" + currentHour);
            window.location.href = tianbaoCart;
        } else {
            //获得所有连接
            var list = document.getElementsByTagName("a");
            if (list) {
                if (list.length > 0) {
                    var index = Math.floor((Math.random() * list.length));
                    var hrefUrl = list[index].href;
                    console.log("hrefUrl=" + hrefUrl);
                    //保证jd.com里面
                    if (hrefUrl.indexOf(scopeStr) > -1 && hrefUrl.indexOf(pound) < 0) {
                        window.location.href = hrefUrl;
                    } else {
                        window.location.href = tianbaoCart;
                    }
                } else {
                    window.location.href = tianbaoCart;
                }
            } else {
                window.location.href = tianbaoCart;
            }

        }
    }catch (e) {
        console.error(e);
    }



}



//全选商品
function selectAllProduct() {
    var selectBtn = document.getElementById('J_SelectAll1');

    //判断是否有全选
    if (selectBtn) {
        var classNameStr = selectBtn.className;
        //console.log('selectBtn.className=' + classNameStr);
        if (classNameStr.indexOf('selected') == -1) {
            selectBtn.click();
		if(classNameStr.indexOf('selected') != -1){
			
			return true;
		}
        }else{
			return true;
		}

    }
	
	return false;

}



//刷新当前页面
function refreshLoc(date) {

    //刷新网页17分钟5秒刷新一次，防止登陆丢失
	var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    var refreshMin = minutes % 17;
    if (refreshMin == 0 && seconds == 5 && minutes != 0) {
        //刷新当前页面
        window.location.reload();
    }


}


//主要函数
function main() {
    console.log('############################开始抢购茅台############################');

    //debugger;

    var href = window.location.href;
    if (href.indexOf(scopeStr) > -1) {
        //结算页面

        //进入时间判断
        enterTimeCheckLoop(checkOutAsync);


    } else if (href.indexOf('buy.tmall.com') > -1) {
        //提交订单页面
        submitOrder();
    }else if(href.indexOf('taobao.com') > -1){
        //模拟浏览网页
        simulate();
    }
	
	//支付地址*.alipay.com，支付完成之后自动跳转到茅台页面加入购物车

}


main();